import requests
import json
import re
import time
# 修改成自己的api key和secret key
API_KEY = "gXT8l7kPabrZkrvCCW2xfNfq"
SECRET_KEY = "KVnzsga2aushS35BFQOaSyFJAruKF4xg"
async def get_information(message):
    try:
        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + get_access_token()
        # 注意message必须是奇数条
        payload = json.dumps({
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ]
        })
        headers = {
            'Content-Type': 'application/json'
        }
        response =requests.request("POST", url, headers=headers, data=payload)
        data=json.loads(response.text)
        result_content=''
        if data:
             result_content =data['result'].replace('\\n', '')

        return result_content
    except Exception as e:

        print(e)
        return 0



def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    data=get_information("中国历史")
    print(data)
